package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

/**
 * Mybatis相关对象
 * @author zhangyan
 * @date 2021/2/1 15:57
 */
public class MybatisConfig {

    /**
     * 方法中的形参对象，是自动从容器中查找，并注入到参数中
     * @Autowired 可以用在参数中,也是自动装配的效果,参数中的@Autowired注解可以省
     *
     * 相当于配置文件的
     *     <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     *         <property name="dataSource" ref="dataSource"></property>
     *         <property name="typeAliasesPackage" value="com.itheima.pojo"></property>
     *     </bean>
     */
    @Bean("sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean(@Autowired DruidDataSource druidDataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //配置数据源
        sqlSessionFactoryBean.setDataSource(druidDataSource);
        //配置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.pojo");

        return sqlSessionFactoryBean;
    }

    /**
     * 相当于配置文件的
     *     <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     *         <property name="basePackage" value="com.itheima.dao"></property>
     *     </bean>
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //指定dao接口包,创建动态代理对象使用
        mapperScannerConfigurer.setBasePackage("com.itheima.dao");

        return mapperScannerConfigurer;
    }
}
